<template>
	<view>
		<block v-if="dataBuffer">
			<view class="item" v-for="(res, index) in siteList" :key="res.id"> <u-icon @click="del(res.id)"
					name="close-circle-fill" :size="40" color="#ff5500" :index="res.id"></u-icon>
				<view class="top" @click="toOrder(res)">
					<view class="name">{{ res.username }}</view>
					<view class="phone">{{ res.userphone }}</view>
					<view class="tag">
						<text class="red" v-if="res.status == 1">默认</text>
					</view>
				</view>
				<view class="bottom">
					{{res.location+res.useraddress}}
					<u-icon @click="edit(res.id)" name="edit-pen" :size="40" color="#999999" :index="res.id"></u-icon>
				</view>
			</view>
		</block>
		<view v-else>
			暂无收货地址信息!
		</view>
		<view class="addSite" @tap="toAddSite">
			<view class="add">
				<u-icon name="plus" color="#ffffff" class="icon" :size="30"></u-icon>新建收货地址
			</view>
		</view>
	</view>
</template>

<script>
	import checkToken from '@/utils/checkToken.js';
	export default {
		data() {
			return {
				siteList: [], //初始化地址数据
				dataBuffer: false
			};
		},
		onShow() {
			let isLogin = checkToken(this);
			// 判断是否登录
			if (!isLogin) {
				uni.showToast({
					title: '请先登录',
					icon: 'error',
					success: () => {
						uni.navigateTo({
							url: '/pages/login/login',
						})
					}
				})
			};

			// 获取缓存数据
			this.userInfo = uni.getStorageSync('userInfo');

			// 发起地址管理请求
			this.requestAddress();
		},
		methods: {
			// 跳转到订单页面
			toOrder(item) {
				uni.setStorage({
					key: 'addressInfo',
					data: item
				});
				uni.navigateTo({
					url: '/pages/order/order',
				});
			},
			// 删除地址
			del(id) {
				uni.showModal({
					title: '提示',
					content: '确定要删除吗?',
					success: (res) => {
						if (res.confirm) {
							// 发起删除请求
							this.$http({
								url: '/api/addressremove',
								method: 'post',
								header: {
									authorization: this.userInfo.token,
								},
								data: {
									id,
								},
							}).then(res => {
								if (res.data.code === 200) {
									uni.showToast({
										title: res.data.msg,
									});
									setTimeout(() => {
										// 更新地址列表
										this.requestAddress();
									}, 1000)
								}
							})
						}
					}
				})
			},
			// 编辑地址
			edit(id) {
				uni.navigateTo({
					url: `/pages/address/addSite?id=${id}`,
				});
			},

			// 发起地址管理请求
			requestAddress() {
				this.$http({
					url: '/api/addresslist',
					header: {
						authorization: this.userInfo.token,
					},
					data: {
						uid: this.userInfo.uid,
					},
				}).then(res => {
					if (res.data.code === 200 && res.data.list != null) {
						this.dataBuffer = true;
						this.siteList = res.data.list;
					} else {
						this.dataBuffer = false;
					}
				})
			},
			// 跳转到新增地址页面
			toAddSite() {
				uni.navigateTo({
					url: './addSite'
				})
			}
		}
	};
</script>

<style lang="scss" scoped>
	// 引入样式
	@import '@/static/css/address.scss';
</style>